import { useEffect, useState } from "react";
import {
  createCounterStore,
  increment,
  decrement,
  getTotal
} from "./store/modules/counterStore";
import { useShallow } from "zustand/react/shallow";

function A() {
  const [num, setNum] = useState("少了少了");
  const { color, price } = createCounterStore(
    useShallow((state) => ({
      color: state.color,
      price: state.price
    }))
  );

  useEffect(() => {
    // const cancelSub = createCounterStore.subscribe((state, prevState) => {
    //   if (state.count > 15 && prevState.count <= 15) {
    //     setNum("多了多了"); // 这里修改了状态，但A组件没有重新渲染
    //   } else if (state.count <= 15 && prevState.count > 15) {
    //     setNum("少了少了");
    //   }
    // });

    const cancelSub = createCounterStore.subscribe(
      (state) => state.count,
      (count, prevCount) => {
        if (count > 15 && (prevCount <= 15 || count === prevCount)) {
          setNum("多了多了"); // 这里修改了状态，但A组件没有重新渲染
        } else if (count <= 15 && (prevCount > 15 || count === prevCount)) {
          setNum("少了少了");
        }
      },
      { equalityFn: () => true, fireImmediately: true }
    );
    return cancelSub;
  }, []);
  console.log("----zustand A----");
  return (
    <div>
      <h1 style={{ color }}>单价：{price}</h1>
      <h1>数量：{num}</h1>
    </div>
  );
}

function B() {
  const { count, price } = createCounterStore();
  const BAdd3 = () => {
    createCounterStore.setState((state) => {
      state.count += 3;
    });
  };
  console.log("----zustand B----");
  return (
    <div className="App">
      hello zustand!
      <h1>单价：{price}</h1>
      <h1>数量：{count}</h1>
      <h1>营业额：{getTotal()}</h1>
      <div>
        <button onClick={increment}>+{count}</button>
        <button onClick={decrement}>-{count}</button>
        <button onClick={BAdd3}>B组件独有的加三动作</button>
      </div>
    </div>
  );
}

function App() {
  return (
    <div className="App">
      <A />
      <B />
    </div>
  );
}

export default App;
